package cn.cena.user.service.impl;

import cn.cena.basic.Exception.MyException;
import cn.cena.basic.util.SendMsg;
import cn.cena.basic.util.StrUtils;
import cn.cena.user.Constant.UserConstant;
import cn.cena.user.domain.User;
import cn.cena.user.mapper.UserMapper;
import cn.cena.user.service.IVerifycodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifycodeServiceImpl implements IVerifycodeService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void sendSmsCode(Map<String,String> params) {
        String phone = params.get("phone");
        String type = params.get("type");
        // 判断phone是否为空
        if(phone == null || type ==null){
            throw new MyException("手机号不能为空");
        }
        // 判断type类型
        if (type.equals("register")){
            // 判断手机号是否注册
            User user = userMapper.findByphone(phone);
            if (user != null){
                throw new MyException("手机号已注册，请直接登录……");
            }
            smsCode(UserConstant.REGISTER_PREFIX + phone);
        }else if (type.equals("binder")){
            smsCode(UserConstant.BINDER_PREFIX + phone);
        }



    }
    public void smsCode(String key){
        Object tempCode = redisTemplate.opsForValue().get(key);
        String code = null;
        // 判断redis中是否过期  时间戳+value
        if (tempCode != null){ // 取到值
            String time = tempCode.toString().split("-")[0]; // 取到时间戳“1515515516”
            // 判断是否超过一分钟
            if (System.currentTimeMillis() - Long.valueOf(time) <= 1 * 60 * 1000) { // 小于一分钟（毫秒计算）
                throw new MyException("验证码已发送，请勿重复发送");
            } else { // 超过一分钟时 将已有验证码重新加时间戳并发送
                code = tempCode.toString().split("-")[1]; // 取到时间戳“1515515516”
            }
        }else { // 没取到值，已过期
            code = StrUtils.getComplexRandomString(4);

        }

        redisTemplate.opsForValue().set(key, System.currentTimeMillis() + "-" + code, 3L, TimeUnit.MINUTES);
//        SendMsg.msgSMS(phone, code + ",有效期：三分钟；");
        System.out.println(redisTemplate.opsForValue().get(key));
    }
}
